<?php

namespace app\common\model;

use think\Model;

/**
 * 升级订单
 */
class GradeOrder extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    /**
     * 处理绿积分
     */
    public static function jifenGreen($goods = [], $userid = '', $orderid = '')
    {
        
        try {
        		error_reporting(0);
        		$total = 0;
        		$shopusers = [];
        		$shoparr = [];
	            foreach($goods as $indes => $goodid){
		            $goodsarr=model('app\api\model\wanlshop\Goods')->where('id', $goodid)->find();
		            $score = $goodsarr['price']*($goodsarr['jifen_green']?:20)/100;
		            $total += $score;

		            //商家
		            $shopuid = model('app\api\model\wanlshop\Shop')->where('id', $goodsarr['shop_id'])->value('user_id');
		            if(in_array($shopuid, $shopusers)){
		            	foreach ($shoparr as $key => $res) {
		            		if ($res['uid'] == $shopuid) {
		            			$shoparr[$key]['val'] = round($res['val'] + $score ,2);
		            		}
		            	}
		            }else{
		            	$shopusers[] = $shopuid;
		            	$shoparr[$indes]['uid'] = $shopuid;
		            	$shoparr[$indes]['val'] = round($score,2);
		            }
		        }
		        $value = round($total,2);

		        // 积分
		        model('app\common\model\Greenjifenlog')->insert([
		        	'user_id' => $userid,
		        	'value' => $value,
		        	'order_id' => $orderid,
		        	'createtime' => time(),
		        	'updatetime' => time()
		        ]);
		        model('app\common\model\User')->where('id',$userid)->inc('jifenuser_green',$value)->update();

		        // 商家积分
		        foreach ($shoparr as $shop){
			        model('app\common\model\Greenjifenlog')->save([
			        	'user_id' => $shop['uid'],
			        	'value' => $shop['val'],
			        	'role' => 1,
			        	'order_id' => $orderid
			        ]);
		        	model('app\common\model\User')->where('id',$shop['uid'])->inc('jifenuser_green',$shop['val'])->update();
		    	}
		        
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

}
